import {loginBack} from '@/utils/loginBack';
import { debounce } from '@/utils/helper';
import { Button, Image, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import React, { useEffect, useRef } from 'react';
import './index.scss';

const WechatLogin = ({ }) => {
  const code = useRef();
  const appConfig = Taro.getStorageSync('appConfig') || {}
  useEffect(() => {
    Taro.login({
      success: (res) => {
        code.current = res.code;
      },
    });
  }, []);

  const getUserPhone = debounce((e) => {
    let loginType = 'WECHAT_MINIPROGRAM'
    if(process.env.TARO_ENV == 'tt'){
      loginType = 'DOUYIN_MOBILE_MINIPROGRAM'
    }
    const { encryptedData, iv, errMsg } = e.detail;
    if (-1 != errMsg.indexOf('ok')) {
      Taro.$post('/mb/logins',{
        username: Taro.$mpAppid,
        loginType,
        password: code.current,
        wechatInfoReq: {
          encryptedData,
          iv,
        },
      }).then(res=>{
        if(res.code == '1'){
          Taro.$toast('登录成功','success')
          setTimeout(() => {
            const timestamp = new Date().getTime();
            if(res.content.userSource == 'USER'){
              Taro.setStorageSync('user',{
                ...res.content,
                loginType,
                timestamp
              });
            }
            Taro.setStorageSync('userSource',res.content.userSource)
            Taro.setStorageSync('token',res.content.token.accessToken)
            loginBack()
          }, 1000);
        }
      })
    } else if (-1 != errMsg.indexOf('deny')) {
      Taro.showModal({
        title: '提示',
        content:
          '您已拒绝，将无法登录使用；如需登录使用，请再次点击微信用户一键登录按钮，并在微信授权窗口点击允许',
      });
    }
  }, 3000);
  const handleUserPhone = debounce((e) => {
    my.getPhoneNumber({
      success: (res) => {
        const data = JSON.parse(res.response)
        Taro.$post('/mb/logins',{
          username: Taro.$mpAppid,
          loginType: 'ALI_MOBILE_MINIPROGRAM',
          password: code.current,
          wechatInfoReq: {
            encryptedData:data.response,
            iv:data.sign,
          },
        }).then(res=>{
          if(res.code == '1'){
            Taro.$toast('登录成功','success')
            setTimeout(() => {
              const timestamp = new Date().getTime();
              if(res.content.userSource == 'USER'){
                Taro.setStorageSync('user',{
                  ...res.content,
                  loginType: 'ALI_MOBILE_MINIPROGRAM',
                  timestamp
                });
              }
              Taro.setStorageSync('userSource',res.content.userSource)
              Taro.setStorageSync('token',res.content.token.accessToken)
              loginBack()
            }, 1000);
          }
        })
      },
      fail: (res) => {
        Taro.$toast(res)
      },
    });
  }, 3000);

  return (
    <View className="WechatLogin">
      <View className="header">欢迎使用 {appConfig?.name}</View>
      <View className="info">立即登录，享受优质服务</View>

      <View className="logo">
        <Image src={appConfig?.iconUrl || require('@/images/gray.jpg')} className="img" />
      </View>
      {process.env.TARO_ENV === 'alipay'?<Button className="btn-blue" openType="getAuthorize" scope="phoneNumber" onGetAuthorize={handleUserPhone} onError={()=>{
        Taro.$toast('取消授权')
      }}>手机号快捷登录</Button>:<Button className="btn-blue" openType="getPhoneNumber" onGetPhoneNumber={getUserPhone}>手机号快捷登录</Button>}
      {/* {agreementInfoLogin?.agreements?.length > 0 && !agreementInfoLogin?.isSelected ? (
        <Button
          className="btn-blue customePageStyleBg50"
          onClick={() => {
            Taro.showToast({
              title: '请勾选并同意协议条款',
              duration: 2000,
              icon: 'none',
            });
          }}
        >
          <View className="txt">手机号快捷登录</View>
        </Button>
      ) : (
        <Button
          className="btn-blue customePageBackgroundStyle"
          openType="getPhoneNumber"
          onGetPhoneNumber={getUserPhone}
        >
          <View className="txt">手机号快捷登录</View>
        </Button>
      )} */}

      <View className="other">
        <View
          className="item"
          onClick={() => {
            Taro.navigateTo({ url: '/pages/other/login/h5/index' });
          }}
        >
          账号密码登录
        </View>
        <View
          className="item"
          onClick={() => {
            Taro.navigateTo({ url: '/pages/other/login/h5/index?mobile=1' });
          }}
        >
          手机号登录
        </View>
      </View>
    </View>
  );
};

export default WechatLogin;